<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,学习笔记,量化投资,Backtrader," />










<meta name="description" content="上次了解了backtrader的基本内容和使用方法。下面就用backtrader框架来解决一个问题:回测一下我的实盘数据。我从2018年开始股票定投，就两个:300etf和纳指etf。开始每个月一次，后来每隔十天一次。由于时间并不绝对固定，没法直接用算法来描述。我从券商APP里把交易记录人肉输入到一个csv文件里，像这样。下面就用backtrader来回测一下。先用tushare下载历史数据并保存">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记73——backtrader实操">
<meta property="og:url" content="https://zwdnet.github.io/2020/07/10/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B073%E2%80%94%E2%80%94backtrader%E5%AE%9E%E6%93%8D/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="上次了解了backtrader的基本内容和使用方法。下面就用backtrader框架来解决一个问题:回测一下我的实盘数据。我从2018年开始股票定投，就两个:300etf和纳指etf。开始每个月一次，后来每隔十天一次。由于时间并不绝对固定，没法直接用算法来描述。我从券商APP里把交易记录人肉输入到一个csv文件里，像这样。下面就用backtrader来回测一下。先用tushare下载历史数据并保存">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-07-10T02:49:51.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="Backtrader">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/07/10/量化投资学习笔记73——backtrader实操/"/>





  <title>量化投资学习笔记73——backtrader实操 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/07/10/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B073%E2%80%94%E2%80%94backtrader%E5%AE%9E%E6%93%8D/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记73——backtrader实操</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-10T02:49:51+00:00">
                2020-07-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>上次了解了backtrader的基本内容和使用方法。下面就用backtrader框架来解决一个问题:回测一下我的实盘数据。<br>我从2018年开始股票定投，就两个:300etf和纳指etf。开始每个月一次，后来每隔十天一次。由于时间并不绝对固定，没法直接用算法来描述。我从券商APP里把交易记录人肉输入到一个csv文件里，像这样。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/01.png"><br>下面就用backtrader来回测一下。先用tushare下载历史数据并保存到文件里。并转换成backtrader可以接受的形式。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getData</span>(<span class="params">code, start, end</span>):</span></span><br><span class="line">    filename = code+<span class="string">&quot;.csv&quot;</span></span><br><span class="line">    print(<span class="string">&quot;./&quot;</span> + filename)</span><br><span class="line">    <span class="comment"># 已有数据文件，直接读取数据</span></span><br><span class="line">    <span class="keyword">if</span> os.path.exists(<span class="string">&quot;./&quot;</span> + filename):</span><br><span class="line">        df = pd.read_csv(filename)</span><br><span class="line">    <span class="keyword">else</span>: <span class="comment"># 没有数据文件，用tushare下载</span></span><br><span class="line">        df = ts.get_k_data(code, autype = <span class="string">&quot;qfq&quot;</span>, start = start, end = end)</span><br><span class="line">        df.to_csv(filename)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    <span class="keyword">return</span> df</span><br></pre></td></tr></table></figure>
<p>下面获取股价数据，并建立数据源。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    start = <span class="string">&quot;2018-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-05-31&quot;</span></span><br><span class="line">    df_300 = getData(<span class="string">&quot;510300&quot;</span>, start, end)</span><br><span class="line">    df_nas = getData(<span class="string">&quot;513100&quot;</span>, start, end)</span><br><span class="line">    print(df_300.info(), df_nas.info())</span><br><span class="line">    <span class="comment"># 建立数据源</span></span><br><span class="line">    start_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, start.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">    end_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, end.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">    data300 = bt.feeds.PandasData(dataname = df_300, name = <span class="string">&quot;300ETF&quot;</span>, fromdate = datetime.datetime(start_date[<span class="number">0</span>], start_date[<span class="number">1</span>], start_date[<span class="number">2</span>]), todate = datetime.datetime(end_date[<span class="number">0</span>], end_date[<span class="number">1</span>], end_date[<span class="number">2</span>]))</span><br><span class="line">    dataNas = bt.feeds.PandasData(dataname = df_nas, name = <span class="string">&quot;nasETF&quot;</span>, fromdate = datetime.datetime(start_date[<span class="number">0</span>], start_date[<span class="number">1</span>], start_date[<span class="number">2</span>]), todate = datetime.datetime(end_date[<span class="number">0</span>], end_date[<span class="number">1</span>], end_date[<span class="number">2</span>]))</span><br></pre></td></tr></table></figure>
<p>下面建立策略类，先写最简单的，直接显示股价。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 交易策略</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TradeStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">            print(<span class="string">&quot;name :%s, price:%.2f&quot;</span> % (data._name, data[<span class="number">0</span>]))</span><br></pre></td></tr></table></figure>
<p>然后建立cerebro实例，加载数据和策略。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 建立回测实例，加载数据，策略。</span></span><br><span class="line">cerebro = bt.Cerebro()</span><br><span class="line">cerebro.addstrategy(TradeStrategy)</span><br><span class="line">cerebro.adddata(data300, name = <span class="string">&quot;300ETF&quot;</span>)</span><br><span class="line">cerebro.adddata(dataNas, name = <span class="string">&quot;nasETF&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>最后运行回测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 运行回测</span></span><br><span class="line">cerebro.run()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/02.png"><br>搞定!<br>接下来，把我的交易记录读入，根据交易记录进行交易。<br>折腾了好久，主要是datetime作为DataFrame的索引，如何找出某个日期的数据呢？用datetime的strftime函数输出字符串，再用loc选取数据。具体看下面。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 交易策略</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TradeStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">            (<span class="string">&quot;recordFilename&quot;</span>, <span class="string">&quot;etfdata.csv&quot;</span>),</span><br><span class="line">    )</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.df_record = pd.read_csv(self.params.recordFilename)</span><br><span class="line">        self.df_record.成交日期 = pd.to_datetime(self.df_record.成交日期, <span class="built_in">format</span> = <span class="string">&quot;%Y%m%d&quot;</span>)</span><br><span class="line">        self.df_record.index = self.df_record.成交日期</span><br><span class="line">        self.df_record.drop(labels = <span class="string">&quot;成交日期&quot;</span>, axis = <span class="number">1</span>, inplace = <span class="literal">True</span>)</span><br><span class="line">        <span class="comment"># print(self.df_record.head(), self.df_record.info())</span></span><br><span class="line">        </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        tradeData = pd.DataFrame()</span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">            date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">            tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                    name = tradeBar.iloc[i].证券名称 </span><br><span class="line">                    price = tradeBar.iloc[i].成交均价 </span><br><span class="line">                    stock = tradeBar.iloc[i].成交量 </span><br><span class="line">                    commit = tradeBar.iloc[i].手续费</span><br></pre></td></tr></table></figure>
<p>下面就要用这些实盘的数据进行回测交易。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        tradeData = pd.DataFrame()</span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">            date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">            tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                    name = tradeBar.iloc[i].证券名称 </span><br><span class="line">                    price = tradeBar.iloc[i].成交均价 </span><br><span class="line">                    stock = tradeBar.iloc[i].成交量 </span><br><span class="line">                    commit = tradeBar.iloc[i].手续费</span><br><span class="line">                    print(<span class="string">&quot;测试&quot;</span>, i, name, price, stock, commit)</span><br><span class="line">                    <span class="comment"># 进行交易</span></span><br><span class="line">                    <span class="keyword">if</span> stock &gt; <span class="number">0</span>:</span><br><span class="line">                        self.broker.add_cash(price*stock + commit + <span class="number">1.0</span>)</span><br><span class="line">                        print(self.broker.get_cash())</span><br><span class="line">                        self.order = self.buy(data = data, size = stock, price = price)</span><br><span class="line">                    <span class="keyword">else</span>:</span><br><span class="line">                        self.order = self.sell(data = data, size = -<span class="number">1</span>*stock, price = price)</span><br></pre></td></tr></table></figure>
<p>跑一下看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/03.png"><br>有两个问题：貌似一个bar里执行了两次，另外买入日期是第二天，因此有交易失败的情况。<br>看了半天，原来是因为我没有判断实盘证券名称与bar数据中的证券名称是否一致的原因。另外查了一下交易的exectype类型:<br>Order.Market或者None：Market订单将以下一个可行的价格进行交易，在回测中，就将以下一根K线的开盘价进行交易。<br>Order.Limit：在给定的价位price或者更好的价位执行的订单。<br>Order.Stop：当价格突破price时，触发订单成交。<br>Order.StopLimit：当价格突破price时触发订单（类似于Order.Stop订单），之后以给定的价位plimit或者更好的价位执行订单（相当于以参数plimit为price的Order.Limit订单）。<br>Order.StopTrailLimit：Order.StopTrail和Order.Limit的组合，按照Order.StopTrail条件触发，按照Order.Limit条件成交。<br>Order.Historical：尚未发现相关说明及应用。<br>以上参考:<a target="_blank" rel="noopener" href="https://blog.csdn.net/m0_46603114/article/details/106031259">https://blog.csdn.net/m0_46603114/article/details/106031259</a><br>看不太明白，我挨个试了一下。最后结果还是第一个，即以第二天开盘价成交的回测结果与实际结果最接近，但还是差了几千块。就先用这个结果吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="keyword">if</span> self.order:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    tradeData = pd.DataFrame()</span><br><span class="line">    orderType = bt.Order.Market</span><br><span class="line">    <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">        date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">        tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">        <span class="comment"># print(&quot;bar数据&quot;, date, data._name)</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                name = tradeBar.iloc[i].证券名称</span><br><span class="line">                price = tradeBar.iloc[i].成交均价</span><br><span class="line">                stock = tradeBar.iloc[i].成交量</span><br><span class="line">                commit = tradeBar.iloc[i].手续费</span><br><span class="line">                <span class="comment"># 进行交易</span></span><br><span class="line">                <span class="keyword">if</span> stock &gt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">                    print(<span class="string">&quot;测试a&quot;</span>, date, name, price, stock, commit)</span><br><span class="line">                    self.broker.add_cash(price*stock + commit)</span><br><span class="line">                    print(self.broker.get_cash())</span><br><span class="line">                    self.order = self.buy(data = data, size = stock, price = price, exectype = orderType)</span><br><span class="line">                <span class="keyword">elif</span> stock &lt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">                    print(<span class="string">&quot;测试b&quot;</span>, date, name, price, stock, commit)</span><br><span class="line">                    self.order = self.sell(data = data, size = -<span class="number">1</span>*stock, price = price, exectype = orderType)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/04.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/05.png"><br>绿色标志是买入点，红色是卖出点，接下来看看画图能不能改进。<br>默认的cerebro.plot()调用有CashValue，Trade，BuySell三个观察器，分别监控总市值，交易盈亏和买卖点。用stdstats参数来控制，默认为True。<br>有三种方法可以改变绘图数据:<br>通过adddata, replaydata和resampledata往cerebro里添加数据。<br>通过addindicator往strategy里添加指标。<br>通过addobserver往cerebro里添加观察器。<br>实操一下，先通过添加观察器增加回撤观察器:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 添加回撤观察器</span></span><br><span class="line">cerebro.addobserver(bt.observers.DrawDown)</span><br></pre></td></tr></table></figure>
<p>再到策略类里实现stop函数。输出策略的最大回撤值:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">stop</span>(<span class="params">self</span>):</span></span><br><span class="line">    self.log(<span class="string">&quot;最大回撤:-%.2f%%&quot;</span> % self.stats.drawdown.maxdrawdown[-<span class="number">1</span>], doprint=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>
<p>输出结果:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/06.png"><br>画的图里也有回撤值的图像。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/07.png"><br>下面试试在strategy里添加indicator，要注意的是任何在__init__()里声明的indicator都会在next()被调用之前被计算。<br>关于绘图，声明Indicator会自动绘图，但通过操作符得到的lines对象不会自动绘图，要绘图可以通过LinePlotterIndicator进行。<br>直接在策略类的__init__()里声明indicators就行啦。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bt.indicators.AroonDown()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/08.png"><br>下面来看看怎么修改图片显示参数。indicators和observers有很多选项可以调整图片显示。有三大类，分别是可以控制整个对象，单独某个lines，和整个系统范围内的图像输出。对于indicators和observers可以设置plotinfo参数，可以在定义是直接指定参数及值，也可以在定义了对象之后，设置对象名.plotinfo.参数名。<br>两个方法都试一下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ad = bt.indicators.AroonDown(plotname = <span class="string">&quot;AD&quot;</span>)</span><br><span class="line">ad.plotinfo.subplot = <span class="literal">False</span></span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/09.png"><br>当subplot参数为False时，图与前面一个图形画在一起，如画移动均线时跟股价画到一起。<br>indicators和observers类中也定义了很多以_开头的函数用来控制绘图。<br>还有控制整个系统绘图的函数，cerebro.plot(),其中numfigs指定分成几张图，默认为1，我改一下看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cerebro.plot(numfigs = <span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>貌似没啥用。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/48/10.png"><br>先这样吧。下面看看怎么加入分析器。<br>用cerebro.addanalyzer函数加入，在run结束后才计算结果，尽管其在内部也是lines。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> backtrader.analyzers <span class="keyword">as</span> btay</span><br></pre></td></tr></table></figure>
<p>先算个夏普比例</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment"># 添加分析对象</span></span><br><span class="line">    cerebro.addanalyzer(btay.SharpeRatio, _name = <span class="string">&quot;sharpe&quot;</span>)</span><br><span class="line">    <span class="comment"># 运行回测</span></span><br><span class="line">    results = cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;夏普比例:&quot;</span>, results[<span class="number">0</span>].analyzers.sharpe.get_analysis())</span><br><span class="line"></span><br><span class="line">夏普比例: OrderedDict([(<span class="string">&#x27;sharperatio&#x27;</span>, <span class="number">0.7071076137019872</span>)])</span><br></pre></td></tr></table></figure>
<p>才0.707，嘿嘿。<br>再加几个试试。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment"># 添加分析对象</span></span><br><span class="line">    cerebro.addanalyzer(btay.SharpeRatio, _name = <span class="string">&quot;sharpe&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.AnnualReturn, _name = <span class="string">&quot;AR&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.DrawDown, _name = <span class="string">&quot;DD&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.Returns, _name = <span class="string">&quot;RE&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.TradeAnalyzer, _name = <span class="string">&quot;TA&quot;</span>)</span><br><span class="line">......</span><br><span class="line">    print(<span class="string">&quot;夏普比例:&quot;</span>, results[<span class="number">0</span>].analyzers.sharpe.get_analysis())</span><br><span class="line">    print(<span class="string">&quot;年化收益率:&quot;</span>, results[<span class="number">0</span>].analyzers.AR.get_analysis())</span><br><span class="line">    print(<span class="string">&quot;回撤:&quot;</span>, results[<span class="number">0</span>].analyzers.DD.get_analysis())</span><br><span class="line">    print(<span class="string">&quot;收益:&quot;</span>, results[<span class="number">0</span>].analyzers.RE.get_analysis())</span><br><span class="line">    print(<span class="string">&quot;交易统计结果:&quot;</span>, results[<span class="number">0</span>].analyzers.TA.get_analysis())</span><br></pre></td></tr></table></figure>
<p>这种方式输出很乱，有两种改进方法，一个是直接输出结果字典的某个键值，还有一个方法是调用分析对象的print()成员函数。两种方法都试试:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">&quot;夏普比例:&quot;</span>, results[<span class="number">0</span>].analyzers.sharpe.get_analysis()[<span class="string">&quot;sharperatio&quot;</span>])</span><br><span class="line">print(<span class="string">&quot;年化收益率:&quot;</span>, results[<span class="number">0</span>].analyzers.AR.get_analysis())</span><br><span class="line">print(<span class="string">&quot;最大回撤:%.2f，最大回撤周期%d&quot;</span> % (results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.drawdown, results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.<span class="built_in">len</span>))</span><br><span class="line">print(<span class="string">&quot;总收益率:%.2f&quot;</span> % (results[<span class="number">0</span>].analyzers.RE.get_analysis()[<span class="string">&quot;rtot&quot;</span>]))</span><br><span class="line">results[<span class="number">0</span>].analyzers.TA.print()</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br></pre></td><td class="code"><pre><span class="line">夏普比例: <span class="number">0.7071076051413587</span></span><br><span class="line">年化收益率: OrderedDict([(<span class="number">2018</span>, <span class="number">2477996.959</span>), (<span class="number">2019</span>, <span class="number">1.80777128840242</span>), (<span class="number">2020</span>, <span class="number">0.15721567033664452</span>)])</span><br><span class="line">最大回撤:<span class="number">15.09</span>，最大回撤周期<span class="number">95</span></span><br><span class="line">总收益率:<span class="number">15.90</span></span><br><span class="line">===============================================================================</span><br><span class="line">TradeAnalyzer:</span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - total:</span><br><span class="line">    - total: <span class="number">5</span></span><br><span class="line">    - <span class="built_in">open</span>: <span class="number">2</span></span><br><span class="line">    - closed: <span class="number">3</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - streak:</span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - won:</span><br><span class="line">      - current: <span class="number">0</span></span><br><span class="line">      - longest: <span class="number">2</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - lost:</span><br><span class="line">      - current: <span class="number">1</span></span><br><span class="line">      - longest: <span class="number">1</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - pnl:</span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - gross:</span><br><span class="line">      - total: <span class="number">8245.700000000004</span></span><br><span class="line">      - average: <span class="number">2748.566666666668</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - net:</span><br><span class="line">      - total: <span class="number">8206.782110000004</span></span><br><span class="line">      - average: <span class="number">2735.5940366666678</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - won:</span><br><span class="line">    - total: <span class="number">2</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - pnl:</span><br><span class="line">      - total: <span class="number">8212.406090000004</span></span><br><span class="line">      - average: <span class="number">4106.203045000002</span></span><br><span class="line">      - <span class="built_in">max</span>: <span class="number">6878.523510000001</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - lost:</span><br><span class="line">    - total: <span class="number">1</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - pnl:</span><br><span class="line">      - total: -<span class="number">5.623979999999938</span></span><br><span class="line">      - average: -<span class="number">5.623979999999938</span></span><br><span class="line">      - <span class="built_in">max</span>: -<span class="number">5.623979999999938</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - long:</span><br><span class="line">    - total: <span class="literal">True</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - pnl:</span><br><span class="line">      - total: <span class="number">8212.406090000004</span></span><br><span class="line">      - average: <span class="number">8212.406090000004</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - won:</span><br><span class="line">        - total: <span class="number">8212.406090000004</span></span><br><span class="line">        - average: <span class="number">4106.203045000002</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">6878.523510000001</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - lost:</span><br><span class="line">        - total: <span class="number">0.0</span></span><br><span class="line">        - average: <span class="number">0.0</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">0.0</span></span><br><span class="line">    - won: <span class="number">2</span></span><br><span class="line">    - lost: <span class="number">0</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - short:</span><br><span class="line">    - total: <span class="number">1</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - pnl:</span><br><span class="line">      - total: -<span class="number">5.623979999999938</span></span><br><span class="line">      - average: -<span class="number">5.623979999999938</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - won:</span><br><span class="line">        - total: <span class="number">0.0</span></span><br><span class="line">        - average: <span class="number">0.0</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">0.0</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - lost:</span><br><span class="line">        - total: -<span class="number">5.623979999999938</span></span><br><span class="line">        - average: -<span class="number">5.623979999999938</span></span><br><span class="line">        - <span class="built_in">max</span>: -<span class="number">5.623979999999938</span></span><br><span class="line">    - won: <span class="number">0</span></span><br><span class="line">    - lost: <span class="number">1</span></span><br><span class="line">  -----------------------------------------------------------------------------</span><br><span class="line">  - <span class="built_in">len</span>:</span><br><span class="line">    - total: <span class="number">958</span></span><br><span class="line">    - average: <span class="number">319.3333333333333</span></span><br><span class="line">    - <span class="built_in">max</span>: <span class="number">479</span></span><br><span class="line">    - <span class="built_in">min</span>: <span class="number">13</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - won:</span><br><span class="line">      - total: <span class="number">945</span></span><br><span class="line">      - average: <span class="number">472.5</span></span><br><span class="line">      - <span class="built_in">max</span>: <span class="number">479</span></span><br><span class="line">      - <span class="built_in">min</span>: <span class="number">466</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - lost:</span><br><span class="line">      - total: <span class="number">13</span></span><br><span class="line">      - average: <span class="number">13.0</span></span><br><span class="line">      - <span class="built_in">max</span>: <span class="number">13</span></span><br><span class="line">      - <span class="built_in">min</span>: <span class="number">13</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - long:</span><br><span class="line">      - total: <span class="number">945</span></span><br><span class="line">      - average: <span class="number">945.0</span></span><br><span class="line">      - <span class="built_in">max</span>: <span class="number">479</span></span><br><span class="line">      - <span class="built_in">min</span>: <span class="number">466</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - won:</span><br><span class="line">        - total: <span class="number">945</span></span><br><span class="line">        - average: <span class="number">472.5</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">479</span></span><br><span class="line">        - <span class="built_in">min</span>: <span class="number">466</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - lost:</span><br><span class="line">        - total: <span class="number">0</span></span><br><span class="line">        - average: <span class="number">0.0</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">0</span></span><br><span class="line">        - <span class="built_in">min</span>: <span class="number">9223372036854775807</span></span><br><span class="line">    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</span><br><span class="line">    - short:</span><br><span class="line">      - total: <span class="number">13</span></span><br><span class="line">      - average: <span class="number">13.0</span></span><br><span class="line">      - <span class="built_in">max</span>: <span class="number">13</span></span><br><span class="line">      - <span class="built_in">min</span>: <span class="number">13</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - won:</span><br><span class="line">        - total: <span class="number">0</span></span><br><span class="line">        - average: <span class="number">0.0</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">0</span></span><br><span class="line">        - <span class="built_in">min</span>: <span class="number">9223372036854775807</span></span><br><span class="line">      *************************************************************************</span><br><span class="line">      - lost:</span><br><span class="line">        - total: <span class="number">13</span></span><br><span class="line">        - average: <span class="number">13.0</span></span><br><span class="line">        - <span class="built_in">max</span>: <span class="number">13</span></span><br><span class="line">        - <span class="built_in">min</span>: <span class="number">13</span></span><br></pre></td></tr></table></figure>
<p>这就清楚多了。<br>现在的问题是计算α，β值的方法，貌似框架里没有直接的方法。下次弄吧，另外想根据《重构》这本书对代码进行一下重构。<br>本文代码： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/46">https://github.com/zwdnet/MyQuant/tree/master/46</a></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/08/%E5%94%87%E6%9E%AA%E8%88%8C%E5%89%91%E8%AE%AE%E6%A0%B9%E5%85%85/" rel="next" title="唇枪舌剑议根充">
                <i class="fa fa-chevron-left"></i> 唇枪舌剑议根充
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/10/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B074%E2%80%94%E2%80%94%E9%80%9A%E8%BF%87%E9%97%AE%E9%A2%98%E5%AD%A6%E7%AE%97%E6%B3%9520-%E5%85%AD%E5%BA%A6%E5%88%86%E7%A6%BB-Six-Degrees-of-Separation/" rel="prev" title="量化投资学习笔记74——通过问题学算法20:六度分离(Six Degrees of Separation)">
                量化投资学习笔记74——通过问题学算法20:六度分离(Six Degrees of Separation) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
